package kr.co.valueworks.fishing.activity;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import kr.co.valueworks.fishing.R;
import kr.co.valueworks.fishing.R.id;
import kr.co.valueworks.fishing.R.layout;
import kr.co.valueworks.fishing.model.FishingDBHelper;
import kr.co.valueworks.fishing.model.WeatherInfo;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import com.luckycatlabs.sunrisesunset.SunriseSunsetCalculator;
import com.luckycatlabs.sunrisesunset.dto.Location;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class FishingDetail extends BaseActivity{

	FishingDBHelper fishingDBHelpler;
	String TAG = this.getClass().getSimpleName();
	final String SEARCH_URL = "http://www.kma.go.kr/wid/searchPoint.jsp?keyword=%s";
	final String WEATHER_URL = "http://www.kma.go.kr/wid/queryDFS.jsp?gridx=%s&gridy=%s";
	
    private static final int DIALOG1_KEY = 0;
    private static final int DIALOG2_KEY = 1;
    private static final int DIALOG3_KEY = 2;
    
    String locality;
    //WeatherInfo wInfo;
    ArrayList<WeatherInfo> weatherInfoList;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fishing_detail);
		
		Intent intent = getIntent();
		String fishingId = intent.getStringExtra("fishingId");
		String fishingName = intent.getStringExtra("fishingName");
		locality = intent.getStringExtra("locality");
		//wInfo = new WeatherInfo();
		weatherInfoList = new ArrayList<WeatherInfo>();
		
		setTitle(fishingName);
		
		showDialog(DIALOG2_KEY);
		
		Thread getWeatherInfoThread = new Thread(){
			public void run(){
				try {
					getWeatherInfo(locality);
				} catch (Exception e) {
					e.printStackTrace();
					//String msg = "날씨 정보를 읽어오는데 실패했습니다.";
					//Toast.makeText(FishingDetail.this, msg, Toast.LENGTH_SHORT).show();					
				} finally{
					mCompleteHandler.sendEmptyMessage(0);					
				}
				
			}
		};
		getWeatherInfoThread.start();
		
		getSunriseSunsetTime();
		/*
		try {

		} catch (Exception e) {
			e.printStackTrace();
			Log.d(TAG, e.getMessage());
			
			String msg = "날씨 정보를 읽어오는데 실패했습니다.";
			Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();			
		}
		*/
		//dismissDialog(DIALOG2_KEY);
		//getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_1);
	}

	public Handler mCompleteHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			//super.handleMessage(msg);
			dismissDialog(DIALOG2_KEY);
			
			int listSize = weatherInfoList.size();
			Log.d("",Integer.toString(listSize));
			// 24시간 정보만 유지
			while(weatherInfoList.size() > 9)
			{
				int lastIdx = weatherInfoList.size();
				weatherInfoList.remove(lastIdx-1);
			}
			
			WeatherAdapter Adapter = new WeatherAdapter(FishingDetail.this, weatherInfoList);

			ListView list = (ListView)findViewById(R.id.weatherListView);
			list.setAdapter(Adapter);
			
			/*
			((TextView)findViewById(R.id.temperature)).setText(wInfo.getTemp());
			((TextView)findViewById(R.id.weather)).setText(wInfo.getWfKor());
			((TextView)findViewById(R.id.windDirection)).setText(wInfo.getWdKor());
			((TextView)findViewById(R.id.windSpeed)).setText(wInfo.getWs());
			*/			
		}

	};
	
	private void getWeatherInfo(String locality)
			throws Exception {
		// 좌표 받아오기
		String pointUrl = String.format(SEARCH_URL, URLEncoder.encode(locality, "euc-kr"));
		String pointXml = loadUrlData(pointUrl);
		Log.d(TAG, pointUrl);
		//Log.d(TAG, pointXml);
		
		Map<String, String> pointMap = new HashMap<String,String>();
		pointMap = getLocalityPoint(pointXml);
		
		String x = pointMap.get("x");
		String y = pointMap.get("y");
		
		if(x != null && y != null)
		{
			// 날씨 정보 받아오기
			String weatherUrl = String.format(WEATHER_URL, x, y);
			String weatherXml = loadUrlData(weatherUrl);
			Log.d(TAG, weatherUrl);
			//Log.d(TAG, weatherXml);
			
			weatherInfoList = getWeather(weatherXml);
		}
		else
		{
			//String msg = "날씨 정보를 읽어오는데 실패했습니다.";
			//Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
			//return;
		}
	}

	private Map<String, String> getLocalityPoint(String pointXml)
			throws XmlPullParserException, IOException {
		Map<String, String> pointMap = new HashMap<String,String>();

		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		XmlPullParser parser = factory.newPullParser();
		parser.setInput(new StringReader(pointXml));

		int parserEvent = parser.getEventType();
		
		String strTag = null;
		boolean isEnd = false;
		while((parserEvent = parser.next()) != XmlPullParser.END_DOCUMENT)
		{
			if(isEnd) break;
			switch (parserEvent)
			{
				case XmlPullParser.START_DOCUMENT:
				// 문서의 시작. 별로 할일 없으니 다음(이벤트)
				break;
				
				case XmlPullParser.END_DOCUMENT:
				//문서의 끝. 별로 할일 없으니 다음(이벤트)
				break;
			
				case XmlPullParser.START_TAG: //시작이벤트를 만나고"<>"
				strTag = parser.getName();
				//      Log.v(" " + parserEvent, strTag);
			
				if(strTag.equals("x"))
				{
					pointMap.put("x", parser.nextText());
					//Log.d(" " + parserEvent, parser.nextText());
				}
				else if(strTag.equals("y"))
				{
					pointMap.put("y", parser.nextText());
					//Log.d(" " + parserEvent, parser.nextText());
				}	
				break;                      
			
				case XmlPullParser.END_TAG: //엔드태그"</>" 를 만났을때
				strTag = parser.getName(); 
				//      Log.v(" " + parserEvent, strTag);
				if (strTag.equals("point")) isEnd = true;	
				
				break;
			
				case XmlPullParser.TEXT:
				break;
			}
		}
		
		return pointMap;
	}

	
	private ArrayList<WeatherInfo> getWeather(String weatherXml)	throws XmlPullParserException, IOException {
		ArrayList<WeatherInfo> list = new ArrayList<WeatherInfo>();
		
		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		XmlPullParser parser = factory.newPullParser();
		parser.setInput(new StringReader(weatherXml));
		
		int parserEvent = parser.getEventType();
		
		String strTag = null;
		boolean isEnd = false;
		WeatherInfo wInfo = new WeatherInfo();
		while((parserEvent = parser.next()) != XmlPullParser.END_DOCUMENT)
		{
			if(isEnd) break;
			switch (parserEvent)
			{
				case XmlPullParser.START_DOCUMENT:
				// 문서의 시작. 별로 할일 없으니 다음(이벤트)
				break;
				
				case XmlPullParser.END_DOCUMENT:
				//문서의 끝. 별로 할일 없으니 다음(이벤트)
				break;
			
				case XmlPullParser.START_TAG: //시작이벤트를 만나고"<>"
				strTag = parser.getName();
				if (strTag.equals("data"))
					wInfo = new WeatherInfo();
				
				//      Log.v(" " + parserEvent, strTag);
				if (strTag.equals("hour"))
					wInfo.setHour(parser.nextText());
				else if(strTag.equals("day"))
					wInfo.setDay(parser.nextText());
				else if(strTag.equals("temp"))
					wInfo.setTemp(parser.nextText());	
				else if(strTag.equals("tmx"))
					wInfo.setTmx(parser.nextText());	
				else if(strTag.equals("sky"))
					wInfo.setSky(parser.nextText());	
				else if(strTag.equals("pty"))
					wInfo.setPty(parser.nextText());	
				else if(strTag.equals("wfKor"))
					wInfo.setWfKor(parser.nextText());	
				else if(strTag.equals("wfEn"))
					wInfo.setWfEn(parser.nextText());	
				else if(strTag.equals("pop"))
					wInfo.setPop(parser.nextText());	
				else if(strTag.equals("r12"))
					wInfo.setR12(parser.nextText());	
				else if(strTag.equals("s12"))
					wInfo.setS12(parser.nextText());	
				else if(strTag.equals("ws"))
					wInfo.setWs(parser.nextText());	
				else if(strTag.equals("wd"))
					wInfo.setWd(parser.nextText());
				else if(strTag.equals("wdKor"))
					wInfo.setWdKor(parser.nextText());
				else if(strTag.equals("wdEn"))
					wInfo.setWdEn(parser.nextText());
				else if(strTag.equals("reh"))
					wInfo.setReh(parser.nextText());			
				
				break;                      
			
				case XmlPullParser.END_TAG: //엔드태그"</>" 를 만났을때
				strTag = parser.getName(); 
				//      Log.v(" " + parserEvent, strTag);
				if (strTag.equals("data"))
				{
					list.add(wInfo);
				}
				break;
			
				case XmlPullParser.TEXT:  
				break;
			}
		}
		
		return list;
	}
	
	private String loadUrlData(String page) throws Exception {
		URL url = new URL(page);
		HttpURLConnection urlConnection =(HttpURLConnection)url.openConnection();
		if(urlConnection == null)return null;
		urlConnection.setConnectTimeout(10000);//최대 10초 대기
		urlConnection.setUseCaches(false);//매번 서버에서 읽어오기
		StringBuilder sb = new StringBuilder();//고속 문자열 결합체
		if(urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
			InputStream inputStream = urlConnection.getInputStream();
			InputStreamReader isr = new InputStreamReader(inputStream);
			
			//한줄씩 읽기
			BufferedReader br = new BufferedReader(isr);
			while(true){
				String line = br.readLine();//웹페이지의 html 코드 읽어오기
				if(line == null)break;//스트림이 끝나면 null리턴
				sb.append(line+"\n");
			}//end while
			br.close();
		}//end if 
		return sb.toString();
	}
	
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG1_KEY: {
                ProgressDialog dialog = new ProgressDialog(this);
                dialog.setTitle("Indeterminate");
                dialog.setMessage("Please wait while loading...");
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                return dialog;
            }
            case DIALOG2_KEY: {
                ProgressDialog dialog = new ProgressDialog(this);
                dialog.setMessage("Please wait while loading...");
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                return dialog;
            }
            case DIALOG3_KEY: {
                ProgressDialog dialog = new ProgressDialog(this);
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                return dialog;
            }            
        }
        return null;
    }
    
    protected void getSunriseSunsetTime()
    {
        Location location = new Location("36.55475208", "128.6428443");
        SunriseSunsetCalculator calculator = new SunriseSunsetCalculator(location, "Asia/Seoul");
        Calendar date = Calendar.getInstance();
        
        String sunriseTime = calculator.getOfficialSunriseForDate(date);
        String sunsetTime = calculator.getOfficialSunsetForDate(date);
        
        ((TextView)findViewById(R.id.sunrise)).setText(sunriseTime);
        ((TextView)findViewById(R.id.sunset)).setText(sunsetTime);
        
        /*
        for(String city : TimeZone.getAvailableIDs())
        {
        	Log.d("",city);
        }
        */

    }
}

class WeatherAdapter extends BaseAdapter {
	LayoutInflater mInflater;
	ArrayList<WeatherInfo> arSrc;

	public WeatherAdapter(Context context, ArrayList<WeatherInfo> arItem) {
		mInflater = (LayoutInflater)context.getSystemService(
				Context.LAYOUT_INFLATER_SERVICE);
		arSrc = arItem;
	}

	@Override
	public int getCount() {
		return arSrc.size();
	}

	@Override
	public Object getItem(int position) {
		return arSrc.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		convertView = mInflater.inflate(R.layout.weather_item, parent, false);
		
		WeatherInfo info = arSrc.get(position);
		
		TextView hour = (TextView)convertView.findViewById(R.id.w_hour);
		TextView day = (TextView)convertView.findViewById(R.id.w_day);
		TextView weather = (TextView)convertView.findViewById(R.id.w_weather_val);
		TextView temper = (TextView)convertView.findViewById(R.id.w_temper_val);
		TextView windDirection = (TextView)convertView.findViewById(R.id.w_windDirection_val);
		TextView windSpeed = (TextView)convertView.findViewById(R.id.w_windSpeed_val);
		ImageView icon = (ImageView)convertView.findViewById(R.id.w_weather_icon);
		
		String strHour = info.getHour() + ":00";
		if(strHour.length() == 4) strHour = "0" + strHour;
		String strDay = info.getDay();
		if(strDay.equals("0")) strDay = "오늘";
		else if(strDay.equals("1")) strDay = "내일";
		else if(strDay.equals("2")) strDay = "모레";
		String strWindDirection = info.getWdKor() + "풍";
		String strWindSpeed = info.getWs();
		if(strWindSpeed.length()>4) strWindSpeed = strWindSpeed.substring(0, 4);
		strWindSpeed = strWindSpeed + "m/s";
		
		int pty = Integer.parseInt(info.getPty());
		int sky = Integer.parseInt(info.getSky());
		if(pty == 1)
			icon.setImageResource(R.drawable.db05);
		else if(pty == 2)
			icon.setImageResource(R.drawable.db06);
		else if(pty == 3)
			icon.setImageResource(R.drawable.db07);
		else if(pty == 4)
			icon.setImageResource(R.drawable.db08);
		else if(sky == 1)
			icon.setImageResource(R.drawable.db01);		
		else if(sky == 2)
			icon.setImageResource(R.drawable.db02);	
		else if(sky == 3)
			icon.setImageResource(R.drawable.db03);	
		else if(sky == 4)
			icon.setImageResource(R.drawable.db04);			

		
		hour.setText(strHour);
		day.setText(strDay);
		weather.setText(info.getWfKor());
		temper.setText(info.getTemp() + "ºC");
		windDirection.setText(strWindDirection);
		windSpeed.setText(strWindSpeed);
		
		return convertView;		
	}

}